package com.orange.core.service.generator;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
@Service
public class CodeGenerateService {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmm");

    private final StringRedisTemplate redisTemplate;

    public String createTimestampCode(String prefix, String redisKey) {
        Long increment = redisTemplate.opsForValue().increment(redisKey);
        if (increment != null && increment == 1L) {
            LocalDateTime now = LocalDateTime.now();
            Duration duration = Duration.between(now, now.toLocalDate().plusDays(1L).atStartOfDay());
            redisTemplate.expire(redisKey, duration.getSeconds(), TimeUnit.SECONDS);
        }
        LocalDateTime now = LocalDateTime.now();
        String timestamp = now.format(FORMATTER);
        return String.format("%s%s%06d", prefix, timestamp, increment);
    }
}
